import csv
import io
import json
from datetime import datetime
from io import BytesIO
from urllib import request as urlrequest
from urllib.error import URLError

from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.core.paginator import Paginator
from django.db.models import Q, Sum
from django.http import JsonResponse
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from .models import (
    AggregatedFinancialReport,
    Department,
    FinanceCategory,
    FinanceRecord,
    FinancialAnalysis,
    UserProfile,
    Company,
)

try:
    import openpyxl  # type: ignore
    from openpyxl.utils import get_column_letter  # type: ignore
except Exception:  # pragma: no cover - optional dependency
    openpyxl = None
    get_column_letter = None  # type: ignore


# 公司管理API接口
@csrf_exempt
@require_http_methods(["GET", "POST"])
def company_list(request):
    """
    公司列表接口
    GET: 获取公司列表（支持分页和搜索）
    POST: 创建新公司
    """
    if request.method == 'GET':
        # 获取查询参数
        page = request.GET.get('page', 1)
        page_size = request.GET.get('page_size', 10)
        search = request.GET.get('search', '')

        # 构建查询
        companies = Company.objects.all()

        # 搜索功能
        if search:
            companies = companies.filter(
                Q(name__icontains=search) |
                Q(legal_person__icontains=search) |
                Q(registration_number__icontains=search)
            )

        # 分页
        paginator = Paginator(companies, page_size)
        companies_page = paginator.get_page(page)

        # 构建响应数据
        companies_data = []
        for company in companies_page:
            companies_data.append({
                'id': company.id,
                'name': company.name,
                'legal_person': company.legal_person,
                'registration_number': company.registration_number,
                'industry': company.industry,
                'registered_capital': str(company.registered_capital),
                'registration_date': company.registration_date.strftime('%Y-%m-%d') if company.registration_date else None,
                'contact_phone': company.contact_phone,
                'contact_email': company.contact_email,
                'created_at': company.created_at.strftime('%Y-%m-%d %H:%M:%S')
            })

        return JsonResponse({
            'success': True,
            'data': companies_data,
            'pagination': {
                'current_page': companies_page.number,
                'total_pages': paginator.num_pages,
                'total_count': paginator.count,
                'has_next': companies_page.has_next(),
                'has_previous': companies_page.has_previous()
            }
        })

    elif request.method == 'POST':
        try:
            data = json.loads(request.body)

            # 验证必填字段
            required_fields = ['name', 'legal_person', 'registration_number', 'industry', 'registered_capital', 'registration_date']
            for field in required_fields:
                if not data.get(field):
                    return JsonResponse({
                        'success': False,
                        'message': f'{field}字段不能为空'
                    }, status=400)

            # 检查公司名称是否已存在
            if Company.objects.filter(name=data['name']).exists():
                return JsonResponse({
                    'success': False,
                    'message': '公司名称已存在'
                }, status=400)

            # 检查统一社会信用代码是否已存在
            if Company.objects.filter(registration_number=data['registration_number']).exists():
                return JsonResponse({
                    'success': False,
                    'message': '统一社会信用代码已存在'
                }, status=400)

            # 创建公司
            company = Company.objects.create(
                name=data['name'],
                legal_person=data['legal_person'],
                registration_number=data['registration_number'],
                industry=data['industry'],
                registered_capital=data['registered_capital'],
                registration_date=data['registration_date'],
                address=data.get('address', ''),
                contact_phone=data.get('contact_phone', ''),
                contact_email=data.get('contact_email', ''),
                description=data.get('description', '')
            )

            return JsonResponse({
                'success': True,
                'message': '公司创建成功',
                'data': {
                    'id': company.id,
                    'name': company.name,
                    'legal_person': company.legal_person,
                    'registration_number': company.registration_number,
                    'industry': company.industry,
                    'registered_capital': str(company.registered_capital),
                    'registration_date': company.registration_date.strftime('%Y-%m-%d'),
                    'address': company.address,
                    'contact_phone': company.contact_phone,
                    'contact_email': company.contact_email,
                    'created_at': company.created_at.strftime('%Y-%m-%d %H:%M:%S')
                }
            }, status=201)

        except json.JSONDecodeError:
            return JsonResponse({
                'success': False,
                'message': 'JSON格式错误'
            }, status=400)
        except Exception as e:
            return JsonResponse({
                'success': False,
                'message': f'创建失败: {str(e)}'
            }, status=500)


@csrf_exempt
@require_http_methods(["GET", "PUT", "DELETE"])
def company_detail(request, company_id):
    """
    公司详情接口
    GET: 获取公司详情
    PUT: 更新公司信息
    DELETE: 删除公司
    """
    try:
        company = Company.objects.get(id=company_id)
    except Exception:
        return JsonResponse({
            'success': False,
            'message': '公司不存在'
        }, status=404)

    if request.method == 'GET':
        return JsonResponse({
            'success': True,
            'data': {
                'id': company.id,
                'name': company.name,
                'legal_person': company.legal_person,
                'registration_number': company.registration_number,
                'industry': company.industry,
                'registered_capital': str(company.registered_capital),
                'registration_date': company.registration_date.strftime('%Y-%m-%d') if company.registration_date else None,
                'address': company.address,
                'contact_phone': company.contact_phone,
                'contact_email': company.contact_email,
                'description': company.description,
                'created_at': company.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'updated_at': company.updated_at.strftime('%Y-%m-%d %H:%M:%S') if company.updated_at else None
            }
        })

    elif request.method == 'PUT':
        try:
            data = json.loads(request.body)

            # 更新公司信息
            if 'name' in data:
                # 检查名称是否与其他公司重复
                if Company.objects.filter(name=data['name']).exclude(id=company_id).exists():
                    return JsonResponse({
                        'success': False,
                        'message': '公司名称已存在'
                    }, status=400)
                company.name = data['name']

            if 'legal_person' in data:
                company.legal_person = data['legal_person']

            if 'registration_number' in data:
                # 检查统一社会信用代码是否与其他公司重复
                if Company.objects.filter(registration_number=data['registration_number']).exclude(id=company_id).exists():
                    return JsonResponse({
                        'success': False,
                        'message': '统一社会信用代码已存在'
                    }, status=400)
                company.registration_number = data['registration_number']

            if 'industry' in data:
                company.industry = data['industry']

            if 'registered_capital' in data:
                company.registered_capital = data['registered_capital']

            if 'registration_date' in data:
                company.registration_date = data['registration_date']

            if 'address' in data:
                company.address = data['address']

            if 'contact_phone' in data:
                company.contact_phone = data['contact_phone']

            if 'contact_email' in data:
                company.contact_email = data['contact_email']

            if 'description' in data:
                company.description = data['description']

            company.save()

            return JsonResponse({
                'success': True,
                'message': '公司更新成功',
                'data': {
                    'id': company.id,
                    'name': company.name,
                    'legal_person': company.legal_person,
                    'registration_number': company.registration_number,
                    'industry': company.industry,
                    'registered_capital': str(company.registered_capital),
                    'registration_date': company.registration_date.strftime('%Y-%m-%d'),
                    'address': company.address,
                    'contact_phone': company.contact_phone,
                    'contact_email': company.contact_email,
                    'created_at': company.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                    'updated_at': company.updated_at.strftime('%Y-%m-%d %H:%M:%S')
                }
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'success': False,
                'message': 'JSON格式错误'
            }, status=400)
        except Exception as e:
            return JsonResponse({
                'success': False,
                'message': f'更新失败: {str(e)}'
            }, status=500)

    elif request.method == 'DELETE':
        # 检查公司是否有部门或用户
        department_count = Department.objects.filter(company=company).count()
        user_count = UserProfile.objects.filter(company=company).count()
        
        if department_count > 0 or user_count > 0:
            return JsonResponse({
                'success': False,
                'message': f'该公司还有{department_count}个部门和{user_count}个用户，无法删除'
            }, status=400)

        company.delete()
        return JsonResponse({
            'success': True,
            'message': '公司删除成功'
        })


# 部门管理API接口
@csrf_exempt
@require_http_methods(["GET", "POST"])
def department_list(request):
    """
    部门列表接口
    GET: 获取部门列表（支持分页和搜索）
    POST: 创建新部门
    """
    if request.method == 'GET':
        # 获取查询参数
        page = request.GET.get('page', 1)
        page_size = request.GET.get('page_size', 10)
        search = request.GET.get('search', '')
        company_id = request.GET.get('company_id', '')

        # 构建查询
        departments = Department.objects.all()
        
        # 按公司筛选
        if company_id:
            departments = departments.filter(company_id=company_id)

        # 搜索功能
        if search:
            departments = departments.filter(
                Q(name__icontains=search) |
                Q(manager__icontains=search)
            )

        # 分页
        paginator = Paginator(departments, page_size)
        departments_page = paginator.get_page(page)

        # 构建响应数据
        departments_data = []
        for dept in departments_page:
            # 获取部门用户数量
            user_count = UserProfile.objects.filter(department=dept).count()

            departments_data.append({
                'id': dept.id,
                'name': dept.name,
                'manager': dept.manager,
                'description': dept.description,
                'company': {
                    'id': dept.company.id,
                    'name': dept.company.name
                } if dept.company else None,
                'created_at': dept.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'user_count': user_count
            })

        return JsonResponse({
            'success': True,
            'data': departments_data,
            'pagination': {
                'current_page': departments_page.number,
                'total_pages': paginator.num_pages,
                'total_count': paginator.count,
                'has_next': departments_page.has_next(),
                'has_previous': departments_page.has_previous()
            }
        })

    elif request.method == 'POST':
        try:
            data = json.loads(request.body)

            # 验证必填字段
            required_fields = ['name', 'manager', 'company_id']
            for field in required_fields:
                if not data.get(field):
                    return JsonResponse({
                        'success': False,
                        'message': f'{field}字段不能为空'
                    }, status=400)

            # 检查部门名称是否已存在（在同一公司内）
            if Department.objects.filter(name=data['name'], company_id=data['company_id']).exists():
                return JsonResponse({
                    'success': False,
                    'message': '部门名称在该公司内已存在'
                }, status=400)

            # 检查公司是否存在
            try:
                company = Company.objects.get(id=data['company_id'])
            except Company.DoesNotExist:
                return JsonResponse({
                    'success': False,
                    'message': '指定的公司不存在'
                }, status=400)

            # 创建部门
            department = Department.objects.create(
                name=data['name'],
                manager=data['manager'],
                description=data.get('description', ''),
                company=company
            )

            return JsonResponse({
                'success': True,
                'message': '部门创建成功',
                'data': {
                    'id': department.id,
                    'name': department.name,
                    'manager': department.manager,
                    'description': department.description,
                    'company': {
                        'id': department.company.id,
                        'name': department.company.name
                    },
                    'created_at': department.created_at.strftime('%Y-%m-%d %H:%M:%S')
                }
            }, status=201)

        except json.JSONDecodeError:
            return JsonResponse({
                'success': False,
                'message': 'JSON格式错误'
            }, status=400)
        except Exception as e:
            return JsonResponse({
                'success': False,
                'message': f'创建失败: {str(e)}'
            }, status=500)


@csrf_exempt
@require_http_methods(["GET", "PUT", "DELETE"])
def department_detail(request, department_id):
    """
    部门详情接口
    GET: 获取部门详情
    PUT: 更新部门信息
    DELETE: 删除部门
    """
    try:
        department = Department.objects.get(id=department_id)
    except Exception:
        return JsonResponse({
            'success': False,
            'message': '部门不存在'
        }, status=404)

    if request.method == 'GET':
        # 获取部门用户列表
        users = UserProfile.objects.filter(department=department).select_related('user')
        users_data = []
        for user in users:
            users_data.append({
                'id': user.id,
                'name': user.user.get_full_name(),
                'username': user.user.username,
                'phone': user.phone,
                'role': user.get_role_display(),
                'hire_date': user.hire_date.strftime('%Y-%m-%d')
            })

        return JsonResponse({
            'success': True,
            'data': {
                'id': department.id,
                'name': department.name,
                'manager': department.manager,
                'description': department.description,
                'created_at': department.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'users': users_data,
                'user_count': len(users_data)
            }
        })

    elif request.method == 'PUT':
        try:
            data = json.loads(request.body)

            # 更新部门信息
            if 'name' in data:
                # 检查名称是否与其他部门重复
                if Department.objects.filter(name=data['name']).exclude(id=department_id).exists():
                    return JsonResponse({
                        'success': False,
                        'message': '部门名称已存在'
                    }, status=400)
                department.name = data['name']

            if 'manager' in data:
                department.manager = data['manager']

            if 'description' in data:
                department.description = data['description']

            department.save()

            return JsonResponse({
                'success': True,
                'message': '部门更新成功',
                'data': {
                    'id': department.id,
                    'name': department.name,
                    'manager': department.manager,
                    'description': department.description,
                    'created_at': department.created_at.strftime('%Y-%m-%d %H:%M:%S')
                }
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'success': False,
                'message': 'JSON格式错误'
            }, status=400)
        except Exception as e:
            return JsonResponse({
                'success': False,
                'message': f'更新失败: {str(e)}'
            }, status=500)

    elif request.method == 'DELETE':
        # 检查部门是否有用户
        user_count = UserProfile.objects.filter(department=department).count()
        if user_count > 0:
            return JsonResponse({
                'success': False,
                'message': f'该部门还有{user_count}个用户，无法删除'
            }, status=400)

        department.delete()
        return JsonResponse({
            'success': True,
            'message': '部门删除成功'
        })


@csrf_exempt
@require_http_methods(["GET"])
def department_stats(request):
    """
    部门统计信息接口
    """
    try:
        # 基本统计
        total_departments = Department.objects.count()
        total_users = UserProfile.objects.count()

        # 各部门用户数量统计
        departments_stats = []
        for dept in Department.objects.all():
            user_count = UserProfile.objects.filter(department=dept).count()
            departments_stats.append({
                'id': dept.id,
                'name': dept.name,
                'manager': dept.manager,
                'user_count': user_count
            })

        # 按用户数量排序
        departments_stats.sort(key=lambda x: x['user_count'], reverse=True)

        return JsonResponse({
            'success': True,
            'data': {
                'total_departments': total_departments,
                'total_users': total_users,
                'departments': departments_stats
            }
        })

    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f'获取统计信息失败: {str(e)}'
        }, status=500)


@csrf_exempt
@require_http_methods(["GET", "POST"])
def finance_records(request):
    """
    财务流水接口：
    GET：获取流水列表（支持分页、筛选）
    POST：创建新的流水记录
    """
    if request.method == "GET":
        page = int(request.GET.get("page", 1))
        page_size = int(request.GET.get("page_size", 10))
        records = FinanceRecord.objects.select_related('company', 'department', 'category', 'user_profile').order_by('-date', '-created_at')

        paginator = Paginator(records, page_size)
        page_obj = paginator.get_page(page)

        data = [{
            'id': r.id,
            'date': r.date.strftime('%Y-%m-%d'),
            'company': r.company.name if r.company else None,
            'department': r.department.name if r.department else None,
            'category': r.category.name if r.category else None,
            'amount': str(r.amount),
            'description': r.description,
            'source': r.source,
            'user_profile': r.user_profile.user.username if r.user_profile else None,
            'created_at': r.created_at.strftime('%Y-%m-%d %H:%M:%S'),
        } for r in page_obj]

        return JsonResponse({
            'success': True,
            'data': data,
            'pagination': {
                'current_page': page_obj.number,
                'total_pages': paginator.num_pages,
                'total_count': paginator.count
            }
        })

    elif request.method == "POST":
        try:
            payload = json.loads(request.body)
            date = payload.get('date')
            company_id = payload.get('company_id')
            department_id = payload.get('department')
            category_id = payload.get('category')
            amount = payload.get('amount')
            description = payload.get('description', '')
            source = payload.get('source', 'manual')

            if not all([date, company_id, department_id, category_id, amount]):
                return JsonResponse({'success': False, 'message': 'date、company_id、department、category、amount 为必填项'}, status=400)

            user_profile = None
            if request.user.is_authenticated and hasattr(request.user, 'profile'):
                user_profile = request.user.profile

            record = FinanceRecord.objects.create(
                date=date,
                company_id=company_id,
                department_id=department_id,
                category_id=category_id,
                amount=amount,
                description=description,
                source=source,
                user_profile=user_profile
            )

            return JsonResponse({
                'success': True,
                'message': '流水创建成功',
                'data': {
                    'id': record.id,
                    'date': record.date,
                    'company': record.company.name,
                    'department': record.department.name,
                    'category': record.category.name,
                    'amount': str(record.amount),
                    'description': record.description,
                    'user_profile': record.user_profile.user.username if record.user_profile else None,
                    'created_at': record.created_at,
                }
            }, status=201)
        except Exception as e:
            return JsonResponse({'success': False, 'message': f'创建失败: {str(e)}'}, status=500)


@csrf_exempt
@require_http_methods(["GET", "POST"])
def aggregated_financial_reports(request):
    """
    GET: 聚合报表列表
    POST: 生成聚合报表，body: { aggregation_type: 'daily'|'weekly'|'monthly'|'quarterly'|'annual', 
                               period: 'YYYY-MM' or 'YYYY-MM-DD' or 'YYYY-WW',
                               company_id: 必填,
                               department_id: 可选,
                               category_id: 可选 }
    """
    if request.method == 'GET':
        # 添加公司筛选
        company_id = request.GET.get('company_id', '')
        reports = AggregatedFinancialReport.objects.all().order_by('-generated_at')
        
        # 按公司筛选
        if company_id:
            reports = reports.filter(report_records__company_id=company_id).distinct()
            
        data = []
        for r in reports:
            data.append({
                'id': r.id,
                'aggregation_type': r.aggregation_type,
                'period': r.period,
                'company': r.company.name if r.company else None,
                'department': r.department.name if r.department else None,
                'category': r.category.name if r.category else None,
                'total_income': str(r.total_income),
                'total_expense': str(r.total_expense),
                'net_profit': str(r.net_profit),
                'transaction_count': r.transaction_count,
                'generated_at': r.generated_at.strftime('%Y-%m-%d %H:%M:%S'),
                'generated_by': r.generated_by.id if r.generated_by else None
            })
        return JsonResponse({'success': True, 'data': data})

    try:
        payload = json.loads(request.body)
        aggregation_type = payload.get('aggregation_type', 'monthly')
        period = payload.get('period')
        company_id = payload.get('company_id')  # 添加公司ID为必填项
        department_id = payload.get('department_id')
        category_id = payload.get('category_id')
        
        if not period or not company_id:
            return JsonResponse({'success': False, 'message': 'period和company_id为必填项'}, status=400)

        # 检查公司是否存在
        try:
            company = Company.objects.get(id=company_id)
        except Company.DoesNotExist:
            return JsonResponse({
                'success': False,
                'message': '指定的公司不存在'
            }, status=400)

        # 构建查询条件
        filter_kwargs = {'date__startswith': period, 'company_id': company_id}
        if department_id:
            filter_kwargs['department_id'] = department_id
        if category_id:
            filter_kwargs['category_id'] = category_id

        records = FinanceRecord.objects.filter(**filter_kwargs)

        # 计算聚合数据
        total_income = records.filter(amount__gt=0).aggregate(v=Sum('amount'))['v'] or 0
        total_expense_abs = records.filter(amount__lt=0).aggregate(v=Sum('amount'))['v'] or 0
        total_expense = abs(total_expense_abs)
        net_profit = total_income - total_expense
        transaction_count = records.count()

        generated_by = None
        if request.user and request.user.is_authenticated:
            try:
                generated_by = request.user.profile
            except Exception:
                generated_by = None

        # 创建聚合报表
        report_data = {
            'aggregation_type': aggregation_type,
            'period': period,
            'company': company,  # 关联公司
            'total_income': total_income,
            'total_expense': total_expense,
            'net_profit': net_profit,
            'transaction_count': transaction_count,
            'generated_by': generated_by
        }
        
        # 添加可选的维度字段
        if department_id:
            report_data['department_id'] = department_id
        if category_id:
            report_data['category_id'] = category_id

        report = AggregatedFinancialReport.objects.create(**report_data)

        return JsonResponse({
            'success': True,
            'message': '聚合报表生成成功',
            'data': {
                'id': report.id,
                'aggregation_type': report.aggregation_type,
                'period': report.period,
                'company': report.company.name if report.company else None,
                'department': report.department.name if report.department else None,
                'category': report.category.name if report.category else None,
                'total_income': str(report.total_income),
                'total_expense': str(report.total_expense),
                'net_profit': str(report.net_profit),
                'transaction_count': report.transaction_count,
                'generated_at': report.generated_at.strftime('%Y-%m-%d %H:%M:%S'),
                'generated_by': report.generated_by.id if report.generated_by else None
            }
        }, status=201)
    except json.JSONDecodeError:
        return JsonResponse({'success': False, 'message': 'JSON格式错误'}, status=400)
    except Exception as e:
        return JsonResponse({'success': False, 'message': f'生成失败: {str(e)}'}, status=500)


@csrf_exempt
@require_http_methods(["GET"])
def aggregated_financial_report_detail(request, report_id):
    try:
        r = AggregatedFinancialReport.objects.get(id=report_id)
        return JsonResponse({
            'success': True,
            'data': {
                'id': r.id,
                'aggregation_type': r.aggregation_type,
                'period': r.period,
                'department': r.department.name if r.department else None,
                'category': r.category.name if r.category else None,
                'total_income': str(r.total_income),
                'total_expense': str(r.total_expense),
                'net_profit': str(r.net_profit),
                'transaction_count': r.transaction_count,
                'ai_insights': r.ai_insights,
                'ai_suggestions': r.ai_suggestions,
                'generated_at': r.generated_at.strftime('%Y-%m-%d %H:%M:%S'),
                'generated_by': r.generated_by.id if r.generated_by else None
            }
        })
    except Exception:
        return JsonResponse({'success': False, 'message': '报表不存在'}, status=404)


@csrf_exempt
@require_http_methods(["POST"])
def aggregated_financial_report_analyze(request, report_id):
    """调用本地部署模型，对聚合报表进行AI分析。"""
    try:
        r = AggregatedFinancialReport.objects.get(id=report_id)
    except Exception:
        return JsonResponse({'success': False, 'message': '报表不存在'}, status=404)

    prompt_data = {
        'aggregation_type': r.aggregation_type,
        'period': r.period,
        'department': r.department.name if r.department else '全部部门',
        'category': r.category.name if r.category else '全部科目',
        'total_income': float(r.total_income),
        'total_expense': float(r.total_expense),
        'net_profit': float(r.net_profit),
        'transaction_count': r.transaction_count
    }

    local_llm_url = 'http://127.0.0.1:8001/llm/analyze'

    key_insights = ''
    ai_suggestions = ''
    risk_level = 'low'

    try:
        data_bytes = json.dumps({'prompt': prompt_data}).encode('utf-8')
        req = urlrequest.Request(local_llm_url, data=data_bytes, headers={'Content-Type': 'application/json'})
        with urlrequest.urlopen(req, timeout=10) as resp:
            resp_body = resp.read().decode('utf-8')
            parsed = json.loads(resp_body)
            key_insights = parsed.get('key_insights') or ''
            ai_suggestions = parsed.get('ai_suggestions') or ''
            risk_level = parsed.get('risk_level') or 'low'
    except (URLError, TimeoutError, ValueError, json.JSONDecodeError):
        key_insights = f"周期 {r.period} 的{r.get_aggregation_type_display()}：收入 {r.total_income} 元，支出 {r.total_expense} 元，净利润 {r.net_profit} 元，交易笔数 {r.transaction_count} 笔。"
        ai_suggestions = '建议对成本构成与现金流进行复核，并关注下期趋势。'
        risk_level = 'medium' if r.net_profit < 0 else 'low'
    except Exception as e:
        return JsonResponse({'success': False, 'message': f'分析失败: {str(e)}'}, status=500)

    # 更新报表的AI分析结果
    r.ai_insights = key_insights
    r.ai_suggestions = ai_suggestions
    r.save()

    # 创建分析记录
    analysis = FinancialAnalysis.objects.create(
        report=r,
        key_insights=key_insights,
        ai_suggestions=ai_suggestions,
        risk_level=risk_level
    )

    return JsonResponse({
        'success': True,
        'message': '分析完成',
        'data': {
            'id': analysis.id,
            'report_id': r.id,
            'key_insights': analysis.key_insights,
            'ai_suggestions': analysis.ai_suggestions,
            'risk_level': analysis.risk_level,
            'created_at': analysis.created_at.strftime('%Y-%m-%d %H:%M:%S')
        }
    }, status=201)


@csrf_exempt
@require_http_methods(["GET"])
def financial_analysis_detail(request, analysis_id):
    try:
        a = FinancialAnalysis.objects.get(id=analysis_id)
        return JsonResponse({
            'success': True,
            'data': {
                'id': a.id,
                'report_id': a.report.id,
                'key_insights': a.key_insights,
                'ai_suggestions': a.ai_suggestions,
                'risk_level': a.risk_level,
                'created_at': a.created_at.strftime('%Y-%m-%d %H:%M:%S')
            }
        })
    except Exception:
        return JsonResponse({'success': False, 'message': '分析记录不存在'}, status=404)


# 用户管理API接口
@csrf_exempt
@require_http_methods(["GET", "POST"])
def user_list(request):
    """
    用户列表接口
    GET: 获取用户列表（支持分页和搜索）
    POST: 创建新用户
    """
    if request.method == 'GET':
        # 获取查询参数
        page = request.GET.get('page', 1)
        page_size = request.GET.get('page_size', 10)
        search = request.GET.get('search', '')
        department_id = request.GET.get('department_id', '')
        company_id = request.GET.get('company_id', '')  # 添加公司筛选

        # 构建查询
        users = User.objects.select_related('profile').all()
        
        # 公司筛选
        if company_id:
            users = users.filter(profile__company_id=company_id)

        # 搜索功能
        if search:
            users = users.filter(
                Q(username__icontains=search) |
                Q(email__icontains=search) |
                Q(profile__phone__icontains=search)
            )

        # 部门筛选
        if department_id:
            users = users.filter(profile__department_id=department_id)

        # 分页
        paginator = Paginator(users, page_size)
        users_page = paginator.get_page(page)

        # 构建响应数据
        users_data = []
        for user in users_page:
            department_info = None
            company_info = None
            if hasattr(user, 'profile'):
                if user.profile.department:
                    department_info = {
                        'id': user.profile.department.id,
                        'name': user.profile.department.name
                    }
                if user.profile.company:
                    company_info = {
                        'id': user.profile.company.id,
                        'name': user.profile.company.name
                    }

            users_data.append({
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'is_active': user.is_active,
                'is_staff': user.is_staff,
                'date_joined': user.date_joined.strftime('%Y-%m-%d %H:%M:%S'),
                'last_login': user.last_login.strftime('%Y-%m-%d %H:%M:%S') if user.last_login else None,
                'profile': {
                    'phone': user.profile.phone if hasattr(user, 'profile') else '',
                    'role': user.profile.role if hasattr(user, 'profile') else '',
                    'role_display': user.profile.get_role_display() if hasattr(user, 'profile') else '',
                    'department': department_info,
                    'company': company_info,
                    'hire_date': user.profile.hire_date.strftime('%Y-%m-%d') if hasattr(user, 'profile') and user.profile.hire_date else None
                } if hasattr(user, 'profile') else None
            })

        return JsonResponse({
            'success': True,
            'data': users_data,
            'pagination': {
                'current_page': users_page.number,
                'total_pages': paginator.num_pages,
                'total_count': paginator.count,
                'has_next': users_page.has_next(),
                'has_previous': users_page.has_previous()
            }
        })

    elif request.method == 'POST':
        try:
            data = json.loads(request.body)

            # 验证必填字段
            required_fields = ['username', 'email', 'password', 'company_id']
            for field in required_fields:
                if not data.get(field):
                    return JsonResponse({
                        'success': False,
                        'message': f'{field}字段不能为空'
                    }, status=400)

            # 检查用户名是否已存在
            if User.objects.filter(username=data['username']).exists():
                return JsonResponse({
                    'success': False,
                    'message': '用户名已存在'
                }, status=400)

            # 检查邮箱是否已存在
            if User.objects.filter(email=data['email']).exists():
                return JsonResponse({
                    'success': False,
                    'message': '邮箱已存在'
                }, status=400)

            # 检查公司是否存在
            try:
                company = Company.objects.get(id=data['company_id'])
            except Company.DoesNotExist:
                return JsonResponse({
                    'success': False,
                    'message': '指定的公司不存在'
                }, status=400)

            # 创建用户
            user = User.objects.create_user(
                username=data['username'],
                email=data['email'],
                password=data['password'],
            )

            # 创建UserProfile并关联公司
            profile_data = {
                'user': user,
                'phone': data.get('phone', ''),
                'role': data.get('role', 'employee'),
                'hire_date': data.get('hire_date', timezone.now().date()),
                'company': company
            }
            
            # 如果提供了部门信息，则关联部门
            if 'department_id' in data and data['department_id']:
                try:
                    department_obj = Department.objects.get(id=data['department_id'], company=company)
                    profile_data['department'] = department_obj
                except Exception:
                    pass  # 部门不存在或不属于该公司则不设置

            UserProfile.objects.create(**profile_data)

            return JsonResponse({
                'success': True,
                'message': '用户创建成功',
                'data': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'phone': user.profile.phone if hasattr(user, 'profile') else '',
                    'role': user.profile.role if hasattr(user, 'profile') else '',
                    'department': user.profile.department.name if hasattr(user, 'profile') and user.profile.department else '',
                    'company': user.profile.company.name if hasattr(user, 'profile') and user.profile.company else '',
                    'date_joined': user.date_joined.strftime('%Y-%m-%d %H:%M:%S')
                }
            }, status=201)

        except json.JSONDecodeError:
            return JsonResponse({
                'success': False,
                'message': 'JSON格式错误'
            }, status=400)
        except Exception as e:
            return JsonResponse({
                'success': False,
                'message': f'创建失败: {str(e)}'
            }, status=500)


@csrf_exempt
@require_http_methods(["GET", "PUT", "DELETE"])
def user_detail(request, user_id):
    """
    用户详情接口
    GET: 获取用户详情
    PUT: 更新用户信息
    DELETE: 删除用户
    """
    try:
        user = User.objects.select_related('profile').get(id=user_id)
    except Exception:
        return JsonResponse({
            'success': False,
            'message': '用户不存在'
        }, status=404)

    if request.method == 'GET':
        department_info = None
        if hasattr(user, 'profile') and user.profile.department:
            department_info = {
                'id': user.profile.department.id,
                'name': user.profile.department.name
            }

        return JsonResponse({
            'success': True,
            'data': {
                'id': user.id,
                'username': user.username,
                'first_name': user.first_name,
                'last_name': user.last_name,
                'email': user.email,
                'is_active': user.is_active,
                'is_staff': user.is_staff,
                'is_superuser': user.is_superuser,
                'date_joined': user.date_joined.strftime('%Y-%m-%d %H:%M:%S'),
                'last_login': user.last_login.strftime('%Y-%m-%d %H:%M:%S') if user.last_login else None,
                'profile': {
                    'phone': user.profile.phone if hasattr(user, 'profile') else '',
                    'role': user.profile.role if hasattr(user, 'profile') else '',
                    'role_display': user.profile.get_role_display() if hasattr(user, 'profile') else '',
                    'department': department_info,
                    'hire_date': user.profile.hire_date.strftime('%Y-%m-%d') if hasattr(user, 'profile') and user.profile.hire_date else None
                } if hasattr(user, 'profile') else None
            }
        })

    elif request.method == 'PUT':
        try:
            data = json.loads(request.body)

            # 更新用户基本信息
            if 'username' in data:
                # 检查用户名是否与其他用户重复
                if User.objects.filter(username=data['username']).exclude(id=user_id).exists():
                    return JsonResponse({
                        'success': False,
                        'message': '用户名已存在'
                    }, status=400)
                user.username = data['username']

            if 'email' in data:
                # 检查邮箱是否与其他用户重复
                if User.objects.filter(email=data['email']).exclude(id=user_id).exists():
                    return JsonResponse({
                        'success': False,
                        'message': '邮箱已存在'
                    }, status=400)
                user.email = data['email']

            if 'is_active' in data:
                user.is_active = data['is_active']

            if 'is_staff' in data:
                user.is_staff = data['is_staff']

            user.save()

            # 更新用户扩展信息
            if hasattr(user, 'profile'):
                profile = user.profile
                if 'phone' in data:
                    profile.phone = data['phone']
                
                if 'role' in data:
                    profile.role = data['role']
                
                if 'hire_date' in data:
                    profile.hire_date = data['hire_date']
                
                if 'department_id' in data:
                    if data['department_id']:
                        try:
                            department_obj = Department.objects.get(id=data['department_id'])
                            profile.department = department_obj
                        except Exception:
                            return JsonResponse({
                                'success': False,
                                'message': '部门不存在'
                            }, status=400)
                    else:
                        profile.department = None
                
                profile.save()
            elif 'phone' in data or 'role' in data or 'department_id' in data or 'hire_date' in data:
                # 如果用户没有profile但提供了profile信息，则创建
                profile_data = {
                    'user': user,
                    'phone': data.get('phone', ''),
                    'role': data.get('role', 'employee'),
                    'hire_date': data.get('hire_date', timezone.now().date())
                }
                
                if 'department_id' in data and data['department_id']:
                    try:
                        department_obj = Department.objects.get(id=data['department_id'])
                        profile_data['department'] = department_obj
                    except Exception:
                        pass  # 部门不存在则不设置

                UserProfile.objects.create(**profile_data)

            department_info = None
            if hasattr(user, 'profile') and user.profile.department:
                department_info = {
                    'id': user.profile.department.id,
                    'name': user.profile.department.name
                }

            return JsonResponse({
                'success': True,
                'message': '用户更新成功',
                'data': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'is_active': user.is_active,
                    'is_staff': user.is_staff,
                    'date_joined': user.date_joined.strftime('%Y-%m-%d %H:%M:%S'),
                    'last_login': user.last_login.strftime('%Y-%m-%d %H:%M:%S') if user.last_login else None,
                    'profile': {
                        'phone': user.profile.phone if hasattr(user, 'profile') else '',
                        'role': user.profile.role if hasattr(user, 'profile') else '',
                        'role_display': user.profile.get_role_display() if hasattr(user, 'profile') else '',
                        'department': department_info,
                        'hire_date': user.profile.hire_date.strftime('%Y-%m-%d') if hasattr(user, 'profile') and user.profile.hire_date else None
                    } if hasattr(user, 'profile') else None
                }
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'success': False,
                'message': 'JSON格式错误'
            }, status=400)
        except Exception as e:
            return JsonResponse({
                'success': False,
                'message': f'更新失败: {str(e)}'
            }, status=500)

    elif request.method == 'DELETE':
        # 确保不删除超级管理员用户
        if user.is_superuser:
            return JsonResponse({
                'success': False,
                'message': '不能删除超级管理员用户'
            }, status=400)

        user.delete()
        return JsonResponse({
            'success': True,
            'message': '用户删除成功'
        })


@csrf_exempt
@require_http_methods(["PUT"])
def user_change_password(request, user_id):
    """
    用户修改密码接口
    PUT: 修改用户密码
    """
    try:
        user = User.objects.get(id=user_id)
    except Exception:
        return JsonResponse({
            'success': False,
            'message': '用户不存在'
        }, status=404)

    try:
        data = json.loads(request.body)
        
        # 验证必填字段
        if not data.get('password'):
            return JsonResponse({
                'success': False,
                'message': '密码不能为空'
            }, status=400)

        # 更新密码
        user.set_password(data['password'])
        user.save()

        return JsonResponse({
            'success': True,
            'message': '密码修改成功'
        })

    except json.JSONDecodeError:
        return JsonResponse({
            'success': False,
            'message': 'JSON格式错误'
        }, status=400)
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f'修改失败: {str(e)}'
        }, status=500)

@csrf_exempt
@require_http_methods(["GET"])
def export_data(request):
    """
    通用导出接口（CSV）。
    GET /api/export/?model=finance_record|financial_report|user_profile&format=csv&...filters
    """
    model_key = request.GET.get('model')
    export_format = (request.GET.get('format') or 'csv').lower()

    if not model_key:
        return JsonResponse({'success': False, 'message': '缺少 model 参数'}, status=400)

    now_str = timezone.now().strftime('%Y%m%d%H%M%S')

    queryset = None
    headers = []
    row_builder = None
    filename = f"export_{model_key}_{now_str}.csv"

    if model_key == 'finance_record':
        queryset = FinanceRecord.objects.select_related('department', 'category', 'user_profile', 'user_profile__user')
        start_date = request.GET.get('start_date')
        end_date = request.GET.get('end_date')
        department_id = request.GET.get('department')
        category_id = request.GET.get('category')

        if start_date:
            try:
                sd = datetime.strptime(start_date, '%Y-%m-%d').date()
                queryset = queryset.filter(date__gte=sd)
            except ValueError:
                return JsonResponse({'success': False, 'message': 'start_date 格式应为 YYYY-MM-DD'}, status=400)
        if end_date:
            try:
                ed = datetime.strptime(end_date, '%Y-%m-%d').date()
                queryset = queryset.filter(date__lte=ed)
            except ValueError:
                return JsonResponse({'success': False, 'message': 'end_date 格式应为 YYYY-MM-DD'}, status=400)
        if department_id:
            queryset = queryset.filter(department_id=department_id)
        if category_id:
            queryset = queryset.filter(category_id=category_id)

        headers = ['ID', '日期', '部门', '科目', '金额', '备注', '来源', '录入人', '创建时间']

        def row_builder(item: FinanceRecord):
            return [
                item.id,
                item.date.strftime('%Y-%m-%d') if hasattr(item.date, 'strftime') else str(item.date),
                item.department.name if item.department else '',
                item.category.name if item.category else '',
                str(item.amount),
                item.description or '',
                item.source,
                (item.user_profile.user.username if item.user_profile and getattr(item.user_profile, 'user', None) else ''),
                item.created_at.strftime('%Y-%m-%d %H:%M:%S') if hasattr(item.created_at, 'strftime') else str(item.created_at),
            ]

    elif model_key == 'financial_report':
        queryset = FinancialReport.objects.select_related('generated_by')
        report_type = request.GET.get('report_type')
        period = request.GET.get('period')
        if report_type:
            queryset = queryset.filter(report_type=report_type)
        if period:
            queryset = queryset.filter(period=period)

        headers = ['ID', '类型', '周期', '总收入', '总支出', '净利润', '生成时间', '生成者ID']

        def row_builder(item: FinancialReport):
            return [
                item.id,
                item.report_type,
                item.period,
                str(item.total_income),
                str(item.total_expense),
                str(item.net_profit),
                item.generated_at.strftime('%Y-%m-%d %H:%M:%S') if hasattr(item.generated_at, 'strftime') else str(item.generated_at),
                item.generated_by.id if item.generated_by else '',
            ]

    elif model_key == 'user_profile':
        queryset = UserProfile.objects.select_related('user', 'department')
        in_service = request.GET.get('in_service')
        if in_service is not None:
            truthy = {'1', 'true', 'yes', 'on', 't'}
            falsy = {'0', 'false', 'no', 'off', 'f'}
            val = in_service.strip().lower()
            if val in truthy:
                queryset = queryset.filter(user__is_active=True)
            elif val in falsy:
                queryset = queryset.filter(user__is_active=False)
            else:
                return JsonResponse({'success': False, 'message': 'in_service 只能为 true/false'}, status=400)

        headers = ['ID', '用户名', '邮箱', '手机号', '角色', '部门', '入职日期', '是否在职']

        def row_builder(item: UserProfile):
            return [
                item.id,
                item.user.username if item.user else '',
                item.user.email if item.user else '',
                item.phone,
                item.get_role_display(),
                item.department.name if item.department else '',
                item.hire_date.strftime('%Y-%m-%d %H:%M:%S') if hasattr(item.hire_date, 'strftime') else str(item.hire_date),
                '是' if (item.user.is_active if item.user else False) else '否',
            ]

    else:
        return JsonResponse({'success': False, 'message': f'不支持的 model: {model_key}'}, status=400)

    from django.http import HttpResponse

    if export_format == 'csv':
        buffer = io.StringIO()
        writer = csv.writer(buffer)
        writer.writerow(headers)
        for obj in queryset.iterator():
            writer.writerow(row_builder(obj))
        csv_content = buffer.getvalue()
        buffer.close()
        response = HttpResponse(csv_content, content_type='text/csv; charset=utf-8')
        response['Content-Disposition'] = f'attachment; filename="{filename}"'
        return response

    if export_format == 'xlsx':
        if openpyxl is None:
            return JsonResponse({'success': False, 'message': '服务器未安装 openpyxl，无法生成 XLSX'}, status=500)

        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = 'Sheet1'
        ws.append(headers)
        for obj in queryset.iterator():
            ws.append(row_builder(obj))

        for col_idx, header in enumerate(headers, start=1):
            max_len = len(str(header))
            for row in ws.iter_rows(min_row=2, min_col=col_idx, max_col=col_idx):
                cell_value = row[0].value
                if cell_value is None:
                    continue
                max_len = max(max_len, len(str(cell_value)))
            ws.column_dimensions[get_column_letter(col_idx)].width = min(max_len + 2, 60)

        output = BytesIO()
        wb.save(output)
        output.seek(0)

        xlsx_filename = filename.replace('.csv', '.xlsx') if filename.endswith('.csv') else f'{filename}.xlsx'
        response = HttpResponse(
            output.read(),
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = f'attachment; filename="{xlsx_filename}"'
        return response

    return JsonResponse({'success': False, 'message': f'不支持的导出格式: {export_format}'}, status=400)

